//
//  OosJsonService.m
//  oos4ios
//
//  Created by Pablo Gonzalez on 7/21/11.
//  Copyright 2011 11870.com. All rights reserved.
//

#import "OosJsonService.h"


@implementation OosJsonService

#define MAX_SHORTURL_ATTEMPTS 5

static NSMutableArray *servicePool;
static NSMutableArray *activeServicePool;

@synthesize query = mQuery;

+ (OosJsonService *)service
{
    if (!servicePool) {
        servicePool = [[NSMutableArray array] retain];
        activeServicePool = [[NSMutableArray array] retain];
    }
    OosJsonService *service;
    if (servicePool.count == 0) {
        service = [[OosJsonService new] autorelease];
    } else {
        @synchronized(servicePool) {
            service = [servicePool lastObject];
            [activeServicePool addObject:service];
            [servicePool removeLastObject];
        }
    }
    return service;
    
}

- (void)dealloc
{
    [mCallback release];
    [receivedData release];
    [mQuery release];
    
    [super dealloc];
}

- (void)read:(id<IOosAtomServiceCallback>)callback
{
    mCallback = [callback retain];
    
    self.query.appToken = [PrivateConstants appKey];
    
    NSURL *requestUrl = [self.query URL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: requestUrl];
    
    [request setHTTPMethod:@"GET"];
    
    receivedData = [[NSMutableData new] retain];
    
    [[[NSURLConnection alloc] initWithRequest: request 
                                     delegate: self 
                             startImmediately: YES] autorelease];
    
}


- (void)connection: (NSURLConnection *)connection 
didReceiveResponse: (NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection: (NSURLConnection *)connection 
    didReceiveData: (NSData *)data
{
    [receivedData appendData:data];
}

- (void)connection: (NSURLConnection *)connection 
  didFailWithError: (NSError *)error
{
    if (attempt < MAX_SHORTURL_ATTEMPTS) {
        attempt++;
        [self read:mCallback];
    } else {
        [mCallback problemWithFetch:error];
    }
}

- (void) recicleService
{
    [receivedData release];
    receivedData = nil;
    attempt = 0;
    [mCallback release];
    mCallback = nil;
    [mQuery release];
    mQuery = nil;
    @synchronized(servicePool) {
        [servicePool insertObject:self atIndex:0];
        [activeServicePool removeObject:self];
    }    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    id response = [[NSString alloc] initWithData: receivedData 
                                               encoding: NSUTF8StringEncoding];
    
    [mCallback receivedFeed:response];
    
    [response release];
    response = nil;
    [self recicleService];
}


@end
